﻿using System;
using System.Collections.Generic;
using System.Data.Entity;
using System.Linq;
using System.Web;
using System.Web.Http;
using System.Web.Mvc;
using System.Web.Optimization;
using System.Web.Routing;
using NITASA.Core.Infrastructure;

namespace NITASA
{
    public class MvcApplication : System.Web.HttpApplication
    {
        protected void Application_Start()
        {
            AreaRegistration.RegisterAllAreas();

            WebApiConfig.Register(GlobalConfiguration.Configuration);
            FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
            RouteConfig.RegisterRoutes(RouteTable.Routes);
            BundleConfig.RegisterBundles(BundleTable.Bundles);
            SetGlobleVariables();
            EngineContext.Initialize(false);
        }

        private void SetGlobleVariables()
        {
            try
            {
                using (NITASA.Data.NTSDBContext context = new Data.NTSDBContext())
                {
                    if (context.Database.Exists())
                    {
                        var CurrentTheme = context.Settings.FirstOrDefault(m => m.Name == "CurrentTheme");
                        if (CurrentTheme != null) Application["CurrentTheme"] = CurrentTheme.Value;
                        else Application["CurrentTheme"] = "Default";
                    }
                    else
                    {
                        Application["CurrentTheme"] = "Default";
                    }
                }
            }
            catch(Exception ex)
            {
                Application["CurrentTheme"] = "Default";
            }
        }

        protected void Application_BeginRequest(Object sender, EventArgs e)
        {
            
        }

        void Application_Error(object sender, EventArgs e)
        {
            if (Request.Url.ToString().ToLower().Contains("/admin/"))
            {
               // Server.TransferRequest("~/Admin/Home/NotFound");
            }
            else
            {
                var ex = HttpContext.Current.Server.GetLastError();
                var httpException = ex as HttpException;
                if (httpException != null && httpException.GetHttpCode() == 500)
                    Server.TransferRequest("~/Home/NotFound500");
                else
                    Server.TransferRequest("~/Home/NotFound404"); //404 error
            }
            Server.ClearError();
        }
    }
}